﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xman.Extensions.Http;
using Xman.Extensions.Core;

namespace Xman.Dashboard.Config
{
    public class ConfigMiddleware
    {
        private const string EmbeddedFileNamespace = "Xman.Dashboard.Config.config_ui_dist";
        private readonly ConfigOptions _options;
        private readonly StaticFileMiddleware _staticFileMiddleware;


        public ConfigMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory, ConfigOptions options)
        {
            _options = (options ?? new ConfigOptions());
            _staticFileMiddleware = CreateStaticFileMiddleware(next, hostingEnv, loggerFactory, options);
        }

        private StaticFileMiddleware CreateStaticFileMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory, ConfigOptions options)
        {
            var staticFileOptions = new StaticFileOptions
            {
                RequestPath = string.IsNullOrEmpty(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}/config_ui_dist",
                FileProvider = new EmbeddedFileProvider(typeof(ConfigMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
            };

            return new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory);
        }


        public async Task Invoke(HttpContext httpContext)
        {
            var httpMethod = httpContext.Request.Method;
            var path = httpContext.Request.Path.Value;

            // 显示配置界面
            if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
            {
                // Use relative redirect to support proxy environments
                var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
                    ? "index.html"
                    : $"{path.Split('/').Last()}/index.html";

                RespondWithRedirect(httpContext.Response, relativeIndexUrl);
                return;
            }
            if (httpMethod == "GET" && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?index.html$", RegexOptions.IgnoreCase))
            {
                await RespondWithIndexHtml(httpContext.Response);
                return;
            }
            //保存配置界面
            if (httpMethod == "POST" && Regex.IsMatch(path, $"^/?{Regex.Escape($"{_options.RoutePrefix}/saveconfig")}/?$", RegexOptions.IgnoreCase))
            {
                await RespondWithSave(httpContext);
                return;
            }
            await _staticFileMiddleware.Invoke(httpContext);
        }

        private void RespondWithRedirect(HttpResponse response, string location)
        {
            response.StatusCode = 301;
            response.Headers["Location"] = location;
        }

        private async Task RespondWithIndexHtml(HttpResponse response)
        {
            response.StatusCode = 200;
            response.ContentType = "text/html;charset=utf-8";

            await using var stream = _options.IndexStream();
            // Inject arguments before writing to response
            var htmlBuilder = new StringBuilder(await new StreamReader(stream).ReadToEndAsync());
            var fileStream = new FileStream(_options.AppsettingsPath, FileMode.Open);
            using (var reader = new StreamReader(fileStream))
            {
                var line = await reader.ReadToEndAsync();
                htmlBuilder.Replace("%(BodyContent)", line);
            }
            await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
        }

        /// <summary>
        /// 返回OK
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private async Task RespondWithSave(HttpContext httpContext)
        {
            var json =(await httpContext.Request.RequestToString()).FormatJson();
            await using var sw = new StreamWriter(_options.AppsettingsPath, false);
            await sw.WriteAsync(json);
        }
    }
}
